---------------------------------------------------------------
-- @Description：         config handler
---------------------------------------------------------------
local skynet = require "skynet"
local log = require "sky_log"
local cc = require "sky_call"
local json = require "json"

local M = {}

--============================= Local Function =============================--
local function fill_servers(robot_plat_config)
    local sql = "select * from manyou_servers"
    local sql_ret = cc.call_mysql("call_sql", tonumber(robot_plat_config.config.plat_id), sql)
    --log.info("fill_servers sql_ret=", sql_ret)

    if sql_ret[1] then 
        for _, v in pairs(sql_ret) do
            local server_info = {}
            server_info.svid = v.svid
            server_info.server_port = tonumber(v.svport)
            server_info.svid_type = v.cid
            server_info.server_ip = v.svip

            if not robot_plat_config.db_info then 
                robot_plat_config.db_info = {}
            end

            if v.svid then 
                robot_plat_config.db_info[tonumber(v.svid)] = server_info
            end
        end
    end
end

local function fill_match_start_time(robot_plat_config)
    local sql = "select * from texas_sngstarttimeset"
    local sql_ret = cc.call_mysql("call_sql", tonumber(robot_plat_config.config.plat_id), sql)
    --log.info("sql_ret=", sql_ret)

    if sql_ret[1] then 
        for _, v in pairs(sql_ret) do
            if v.svid 
            and robot_plat_config.db_info[tonumber(v.svid)] then 
                robot_plat_config.db_info[tonumber(v.svid)].match_start_timestamp = v.startgametime
                robot_plat_config.db_info[tonumber(v.svid)].rewardtype = v.rewardtype
            end
        end
    end
end

local function fill_tables(robot_plat_config)
    local sql = "select * from texas_tables"
    local sql_ret = cc.call_mysql("call_sql", tonumber(robot_plat_config.config.plat_id), sql)
    --log.info("sql_ret=", sql_ret)

    if sql_ret[1] then 
        for _, v in pairs(sql_ret) do
            if v.svid 
            and robot_plat_config.db_info[tonumber(v.svid)] then 
                if not robot_plat_config.db_info[tonumber(v.svid)].tables then
                    robot_plat_config.db_info[tonumber(v.svid)].tables = {}
                end

                local temp_t = {}
                temp_t.tid = v.tid
                temp_t.svid = v.svid
                temp_t.table_type = v.ttype
                temp_t.buy_min = v.tbuymin
                temp_t.buy_max = v.tbuymax
                temp_t.max_player = v.tplayermax
                temp_t.chipin_time = v.chipinTime
                temp_t.addr_limit = v.IsAddr
                temp_t.big_blind = v.tblindmin * 2
                temp_t.is_private = v.privateRoom
                temp_t.tattr = v.tattr

                robot_plat_config.db_info[tonumber(v.svid)].tables[tonumber(v.tid)] = temp_t
            end
        end
    end
end

local function fill_sngtable(robot_plat_config)
    local sql = "select * from texas_sngtables"
    local sql_ret = cc.call_mysql("call_sql", tonumber(robot_plat_config.config.plat_id), sql)
    --log.info("sql_ret=", sql_ret)

    if sql_ret[1] then 
        for _, v in pairs(sql_ret) do
            if tonumber(v.svid) and (v.tid)
            and robot_plat_config.db_info[tonumber(v.svid)]
            and robot_plat_config.db_info[tonumber(v.svid)].tables
            and robot_plat_config.db_info[tonumber(v.svid)].tables[tonumber(v.tid)] then 
                robot_plat_config.db_info[tonumber(v.svid)].tables[tonumber(v.tid)].solevel = v.solevel
            end
        end
    end
end

local function load_ini(filename)
    local data = {}
    local session = nil
    local file = io.open(filename, "r")
    if not file then
        return  false
    end

    for line in file:lines() do
        line = string.sub(line, 1, (string.find(line, "#") or string.find(line, ";") or (string.len(line) + 1)) - 1)
        if line ~= "" then
            --session
            local s = line:match("%[(.+)%]")
            if s then 
                session = s
            elseif session then 
                --find '='
                local epos = string.find(line, "=") 
                if epos and (epos ~= 1) and (epos ~= string.len(line)) then
                    if data[session] == nil then                
                        data[session] = {}
                    end
                    data[session][string.sub(line, 1, epos - 1)] = string.sub(line, epos + 1)
                end
            end
        end
    end

    file:close()

    return data
end

local function fill_config_data(robot_plat_config, robot_plat_config_raw, plat_id)
    if robot_plat_config_raw then 
        robot_plat_config[plat_id] = {}
        robot_plat_config[plat_id].config = {}
        robot_plat_config[plat_id].config.plat_id = plat_id
        --memdb
        robot_plat_config[plat_id].config.mem_db_server_port = (robot_plat_config_raw[plat_id].MemdbServer or {}).MEMDBPORT
        robot_plat_config[plat_id].config.mem_db_server_ip = (robot_plat_config_raw[plat_id].MemdbServer or {}).MEMDBHOST
        --memcache
        robot_plat_config[plat_id].config.memcache_uid = (robot_plat_config_raw[plat_id].MemCached or {}).MEMCACHEDHOST_MID
        robot_plat_config[plat_id].config.memcache_signup = (robot_plat_config_raw[plat_id].MemCached or {}).MEMCACHEDHOST_SIGNUP
        robot_plat_config[plat_id].config.memcache_exp = (robot_plat_config_raw[plat_id].MemCached or {}).MEMCACHEDHOST_EXP
        robot_plat_config[plat_id].config.memcache_tid = (robot_plat_config_raw[plat_id].MemCached or {}).MEMCACHEDHOST_TID
        --mysql
        robot_plat_config[plat_id].config.mysql_db = (robot_plat_config_raw[plat_id].GameServer or {}).DB
        robot_plat_config[plat_id].config.mysql_host = (robot_plat_config_raw[plat_id].GameServer or {}).HOST
        robot_plat_config[plat_id].config.mysql_password = (robot_plat_config_raw[plat_id].GameServer or {}).PARSSWORD
        robot_plat_config[plat_id].config.mysql_port = (robot_plat_config_raw[plat_id].GameServer or {}).PORT
        robot_plat_config[plat_id].config.mysql_user = (robot_plat_config_raw[plat_id].GameServer or {}).USER
        robot_plat_config[plat_id].config.mysql_socket = (robot_plat_config_raw[plat_id].GameServer or {}).SOCKET
        --redis
        robot_plat_config[plat_id].config.redis_ext_host = (robot_plat_config_raw[plat_id].MemCached or {}).REDISHOST_EXT
        robot_plat_config[plat_id].config.redis_ext_passwd = (robot_plat_config_raw[plat_id].MemCached or {}).REDISHOST_EXT_PASSWD
        robot_plat_config[plat_id].config.redis_tid_host = (robot_plat_config_raw[plat_id].MemCached or {}).REDISHOST_TID
        robot_plat_config[plat_id].config.redis_tid_passwd = (robot_plat_config_raw[plat_id].MemCached or {}).REDISHOST_TID_PASSWD
        robot_plat_config[plat_id].config.redis_gi_host = (robot_plat_config_raw[plat_id].MemCached or {}).REDISHOST_GI
        robot_plat_config[plat_id].config.redis_gi_passwd = (robot_plat_config_raw[plat_id].MemCached or {}).REDISHOST_GI_PASSWD
        robot_plat_config[plat_id].config.redis_lottery_host = (robot_plat_config_raw[plat_id].MemCached or {}).REDISHOST_LOTTERY
        robot_plat_config[plat_id].config.redis_lottery_passwd = (robot_plat_config_raw[plat_id].MemCached or {}).REDISHOST_LOTTERY_PASSWD
        robot_plat_config[plat_id].config.need_auth = (robot_plat_config_raw[plat_id].MemCached or {}).IF_REDIS_AUTH

        log.warning("fill_config_data success: ", plat_id)
    end
end

local function fill_mysql_data(robot_plat_config)
    if not robot_plat_config 
    or not robot_plat_config.config 
    or not robot_plat_config.config.plat_id then 
        log.error("fill_mysql_data error : robot_plat_config=", robot_plat_config)
        return
    end

    cc.call_mysql("init_by_config", robot_plat_config.config)

    fill_servers(robot_plat_config)
    fill_match_start_time(robot_plat_config)
    fill_tables(robot_plat_config)
    fill_sngtable(robot_plat_config)
end

local function fill_memcache_data(robot_plat_config)
    cc.call_memcache("init_by_config", robot_plat_config.config)
end

local function fill_memdb_data(robot_plat_config)
    cc.call_memdb("init_by_config", robot_plat_config.config)
end

local function fill_redis_data(robot_plat_config)
    skynet.call(".redis", "lua", "init_by_config", robot_plat_config.config)
end

local function check_robot_type(robot_config, plat_id)
    if not plat_id then 
        log.error("fill_ac_map error : plat_id==nil")
        return
    end

    local sql = "desc texas_robot robottype"
    local sql_ret = cc.call_mysql("call_sql", plat_id, sql)
    --log.info("sql_ret=", sql_ret)
end

local function fill_robot_que_with_type(robot_config, plat_id)
    if not plat_id then 
        log.error("fill_robot_que_with_type error : plat_id==nil")
        return
    end
    if not robot_config[tonumber(plat_id)] then 
        robot_config[tonumber(plat_id)] = {}
    end

    local sql = "select robottype, count(*) num from texas_robot group by robottype"
    local sql_ret = cc.call_mysql("call_sql", plat_id, sql)
    if not sql_ret[1] then 
        log.error("fill_robot_que_with_type error1 ")
        return
    end

    local count = 0
    for _, v in pairs(sql_ret) do
        local robot_type = v.robottype 
        if not robot_config[tonumber(plat_id)][robot_type] then 
            robot_config[tonumber(plat_id)][robot_type] = {}
        end
        sql = "select * from texas_robot where active=1 and robottype="..robot_type.." order by rand()"
        sql_ret = cc.call_mysql("call_sql", plat_id, sql)
        --log.info("sql_ret=", sql_ret)
        --log.info("robot_type=", robot_type)

        if sql_ret[1] then 
            for _, robot in pairs(sql_ret) do
                if robot.id then 
                    --self.robot_config[robot_type][robot.id] = robot
                    table.insert(robot_config[tonumber(plat_id)][robot_type], robot)
                    count = count + 1
                    --[[
                    if count>6 then
                        break
                    end
                    --]]
                end
            end
        end
    end

    log.warning("init robot_config ["..count.."] success!")
    --log.warning("###############init robot_config success!###############")
end

local function fill_ac_map(ac_map, plat_id)
    if not plat_id then 
        log.error("fill_ac_map error : plat_id==nil")
        return
    end
    if not ac_map[tonumber(plat_id)] then 
        ac_map[tonumber(plat_id)] = {}
    end

    local sql = "select * from manyou_ac"
    local sql_ret = cc.call_mysql("call_sql", plat_id, sql)
    --log.info("sql_ret=", sql_ret)

    if not sql_ret
    or not sql_ret[1] then 
        log.error("fill_ac_map error sql=", sql)
        return
    end
    for _, v in pairs(sql_ret) do
        table.insert(ac_map[tonumber(plat_id)], v)
    end

    log.warning("init ac_map success!")
    --log.warning("###############init ac_map success!###############")
end

local function fill_special_tarneeb_cfg(tarneeb_cfg, plat_id)
    local sql = "select * from texas_kv;"
    local sql_ret = cc.call_mysql("call_sql", tonumber(plat_id), sql)
    --log.info("sql_ret=", sql_ret)

    if sql_ret and type(sql_ret)=='table' then 
        for _, v in pairs(sql_ret) do
            if  (v.id=="appcfg__Tarneeb_room__on")
            or (v.id =="appcfg__Tarneeb_room__demo") then
                tarneeb_cfg[plat_id] = json.decode(v.cfg)
            end
        end
    end
end

function M.init_plat_config(self, plat_id, plat_config)
    if not plat_id then 
        log.error("init_plat_config error : plat_id==nil")
        return
    end

    local file_data = load_ini(plat_config)
    if file_data then 
        log.warning("####################config "..plat_id.." start####################")
        self.robot_plat_config_raw[tonumber(plat_id)] = file_data
        fill_config_data(self.robot_plat_config, self.robot_plat_config_raw, tonumber(plat_id))
        --mysql
        fill_mysql_data(self.robot_plat_config[tonumber(plat_id)])
        --memcache
        fill_memcache_data(self.robot_plat_config[tonumber(plat_id)])
        --memdb
        fill_memdb_data(self.robot_plat_config[tonumber(plat_id)])
        --redis
        fill_redis_data(self.robot_plat_config[tonumber(plat_id)])
        
        --robot
        --check_robot_type(self.robot_config, tonumber(plat_id))
        fill_robot_que_with_type(self.robot_config, tonumber(plat_id))

        --ac_map
        fill_ac_map(self.ac_map, tonumber(plat_id))

        fill_special_tarneeb_cfg(self.special_tarneeb_config, tonumber(plat_id))

        log.warning("####################config "..plat_id.." end####################")
        return true
    else
        log.error("init_plat_config error!", " plat_id="..plat_id
            .." plat_config="..plat_config)
    end

    return false
end

return M